/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.sunspotworld;

import com.sun.spot.core.util.Utils;
import com.sun.spot.ipv6.util.Mutex;
import java.util.Random;

/**
 *
 * @author me
 */
public class BoundedBuffer {
    private int [] buffer = new int[20];

    private int MAX = 20;
    private int getix = 0;
    private int putix = 0;
    private int numberofelements = 0;

    private Random generator = new Random();
    private Mutex mutex = new Mutex();
    private boolean isProtected;

    public BoundedBuffer(boolean useProtection) {
        isProtected = useProtection;
    }

    private synchronized void synchedWait() throws InterruptedException {
        wait();
    }

    public int get(){
        if (isProtected) {
            mutex.lock();
        }
        while (numberofelements == 0) {
            try {
                synchedWait();
            } catch (InterruptedException e) {
                System.out.println("get().wait() Exception");
            }
        }
        int tempbuf = buffer[getix];
        System.out.println("numberofelements(before get) is = " +numberofelements);
        System.out.println("Got: " +tempbuf+ " from "+getix);
        getix = (getix +1) % MAX ;

        int tempne = numberofelements;

        int waitTime = 1 + generator.nextInt(9) * 10;
        Utils.sleep(waitTime);

        numberofelements = tempne-1;
        if (isProtected) {
            mutex.unlock();
        }
        synchedNotify();
        return tempbuf;
    }

    private synchronized void synchedNotify() {
        notify();
    }

    public void put(int value){
        if (isProtected) {
            mutex.lock();
        }
        while(numberofelements >= MAX) {
            try{
                synchedWait();
            } catch (InterruptedException e) {
                System.out.println("put().wait() Exception");
            }
        }
        buffer[putix] = value;
        System.out.println("numberofelements(before put) is = " +numberofelements);
        System.out.println("Put: " +value+ " in "+ putix);

        putix = (putix +1) % MAX;

        int tempel = numberofelements;

        int waitTime = 1 + generator.nextInt(9) * 10;
        Utils.sleep(waitTime);

        numberofelements = tempel+1;

        if (isProtected) {
            mutex.unlock();
        }
        synchedNotify();
    }
}
